// 元素尺寸变动的指令
import { inject, onBeforeUnmount } from 'vue';

export default {
  mounted (el, binding, vnode) {
    const observer = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const width = entry.contentRect.width;
        const height = entry.contentRect.height;

        // 更新组件中的数据
        vnode.ctx.emit('resize', { width, height });
      }
    });

    observer.observe(el);

    // 当 directive 被解绑时，取消观察
    onBeforeUnmount(() => {
      observer.disconnect();
    });
  }
};
